﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.IO;
using ImageTools.IO.Gif;
using ImageTools.IO.Jpeg;
using System.Diagnostics;

namespace Code4WP7SDK.Controls
{
    public class NextPlaceImage : Control
    {

        #region Constructor
        public NextPlaceImage()
        {
            DefaultStyleKey = typeof(NextPlaceImage);
        }
        #endregion

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            // Get template parts
            _backImage = GetTemplateChild("BackImage") as Image;
            _frontImage = GetTemplateChild("FrontImage") as Image;
            _frontImageLoaded = false;

            // Set Bindings and hook up to new elements
            if (null != _backImage)
            {
                BitmapImage backbitImage = new BitmapImage();
                backbitImage.UriSource = new Uri(this.DefaultImageSource, UriKind.Relative);
                _backImage.Source = backbitImage;
                _backImage.SetBinding(Image.StretchProperty, new Binding("Stretch") { Source = this });
            }
            if (null != _frontImage)
            {
                if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
                {
                    BitmapImage frontbitImage = new BitmapImage();
                    lock (_frontImage)
                    {
                        if (!string.IsNullOrEmpty(this.RealImageSource))
                        {
                            WebClient ws = new WebClient();
                            ws.OpenReadCompleted += (s, e) =>
                            {
                                if (e.Error == null)
                                {
                                    Stream stream = (Stream)e.Result;
                                    if (this.RealImageSource.Contains(".gif"))
                                    {
                                        GifDecoder gd = new GifDecoder();
                                        ImageTools.ExtendedImage image = new ImageTools.ExtendedImage();
                                        gd.Decode(image, stream);
                                        JpegEncoder jpeg = new JpegEncoder();
                                        using (MemoryStream mstream = new MemoryStream())
                                        {
                                            jpeg.Encode(image, mstream);
                                            frontbitImage.SetSource(mstream);
                                        }
                                    }
                                    else
                                    {
                                        frontbitImage.SetSource(stream);
                                    }
                                    _frontImageLoaded = true;
                                }
                            };
                            ws.OpenReadAsync(new Uri(this.RealImageSource), UriKind.Absolute);
                        }
                        else
                        {
                            _frontImageLoaded = true;
                            frontbitImage.UriSource = new Uri("", UriKind.RelativeOrAbsolute);
                        }
                        _frontImage.Source = frontbitImage;
                        UpdateBackImageVisibility();
                    }
                    _frontImage.SetBinding(Image.StretchProperty, new Binding("Stretch") { Source = this });
                }
                // Update display
                UpdateBackImageVisibility();
            }
        }

        #region Fields
        private Image _backImage;
        private Image _frontImage;
        private bool _frontImageLoaded;

        #endregion

        #region DependencyProperties
        public string DefaultImageSource
        {
            get { return (string)GetValue(DefaultImageSourceProperty); }
            set { SetValue(DefaultImageSourceProperty, value); }
        }

        public static readonly DependencyProperty DefaultImageSourceProperty =
            DependencyProperty.Register("DefaultImageSource", typeof(string), typeof(NextPlaceImage), null);


        public string RealImageSource
        {
            get { return (string)GetValue(RealImageSourceProperty); }
            set { SetValue(RealImageSourceProperty, value); }
        }

        public static readonly DependencyProperty RealImageSourceProperty =
            DependencyProperty.Register("RealImageSource", typeof(string), typeof(NextPlaceImage), new PropertyMetadata(OnSourcePropertyChanged));

        public static void OnSourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            NextPlaceImage npi = (NextPlaceImage)obj;
            npi.OnSourcePropertyChanged((string)args.OldValue, (string)args.NewValue);
        }

        private void OnSourcePropertyChanged(string oldValue, string newValue)
        {

            _frontImageLoaded = false;
            UpdateBackImageVisibility();
        }

        public Stretch Stretch
        {
            get { return (Stretch)GetValue(StretchProperty); }
            set { SetValue(StretchProperty, value); }
        }

        public static readonly DependencyProperty StretchProperty =
            DependencyProperty.Register("Stretch", typeof(Stretch), typeof(NextPlaceImage), new PropertyMetadata(Stretch.Uniform));
        #endregion

        #region Method
        private void UpdateBackImageVisibility()
        {
            if (null != _backImage)
            {
                _backImage.Visibility = _frontImageLoaded ? Visibility.Collapsed : Visibility.Visible;
            }
        }
        #endregion
        
        
    }
}
